<template>
  <div class="dashboard-container">
    <!-- 第一个图表：时间维度统计 -->
    <div class="exam-statistics-container">
      <div class="header">
        <h2>考研数学考试分析</h2>
        <div class="time-dimension-selector">
          <el-radio-group v-model="timeDimension" @change="fetchTimeData">
            <el-radio-button label="day">按天</el-radio-button>
            <el-radio-button label="week">按周</el-radio-button>
            <el-radio-button label="month">按月</el-radio-button>
            <el-radio-button label="year">按年</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <div class="chart-container">
        <div ref="timeChart" style="width: 100%; height: 500px;"></div>
      </div>

      <div class="data-table" v-if="timeStatisticsData.length > 0">
        <el-table :data="timeStatisticsData" border style="width: 100%">
          <el-table-column prop="timePeriod" label="时间周期" width="180"></el-table-column>
          <el-table-column prop="examCount" label="考试次数" width="120"></el-table-column>
          <el-table-column prop="avgCorrectRate" label="平均正确率(%)">
            <template #default="{ row }">
              <el-progress :percentage="row.avgCorrectRate" :color="getProgressColor(row.avgCorrectRate)"
                :show-text="false" />
              {{ row.avgCorrectRate.toFixed(2) }}%
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 第二个图表：分数分布统计 -->
    <div class="exam-statistics-container" style="margin-top: 30px;">
      <div class="header">
        <h2>考研数学分数分布统计</h2>
        <div class="exam-type-selector">
          <el-radio-group v-model="examType" @change="fetchScoreData">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="数一">数一</el-radio-button>
            <el-radio-button label="数二">数二</el-radio-button>
            <el-radio-button label="数三">数三</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <div class="chart-container">
        <div ref="scoreChart" style="width: 100%; height: 500px;"></div>
      </div>

      <div class="data-table" v-if="scoreStatisticsData.length > 0">
        <el-table :data="scoreStatisticsData" border style="width: 100%">
          <el-table-column prop="examType" label="考试类型" width="120"></el-table-column>
          <el-table-column label="0-20分">
            <template #default="{ row }">
              {{ row.range0_20Count }} ({{ row.range0_20Percent }}%)
            </template>
          </el-table-column>
          <el-table-column label="21-40分">
            <template #default="{ row }">
              {{ row.range21_40Count }} ({{ row.range21_40Percent }}%)
            </template>
          </el-table-column>
          <el-table-column label="41-60分">
            <template #default="{ row }">
              {{ row.range41_60Count }} ({{ row.range41_60Percent }}%)
            </template>
          </el-table-column>
          <el-table-column label="61-70分">
            <template #default="{ row }">
              {{ row.range61_70Count }} ({{ row.range61_70Percent }}%)
            </template>
          </el-table-column>
          <el-table-column label="71-80分">
            <template #default="{ row }">
              {{ row.range71_80Count }} ({{ row.range71_80Percent }}%)
            </template>
          </el-table-column>
          <el-table-column prop="totalCount" label="总人数"></el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'ExamDashboard',
  setup() {
    // 第一个图表相关变量
    const timeChart = ref(null)
    let timeChartInstance = null
    const timeDimension = ref('week')
    const timeStatisticsData = ref([])
    const timeLoading = ref(false)

    // 第二个图表相关变量
    const scoreChart = ref(null)
    let scoreChartInstance = null
    const examType = ref('all')
    const scoreStatisticsData = ref([])
    const scoreLoading = ref(false)

    // 初始化图表
    const initCharts = () => {
      if (timeChart.value) {
        timeChartInstance = echarts.init(timeChart.value)
      }
      if (scoreChart.value) {
        scoreChartInstance = echarts.init(scoreChart.value)
      }
      window.addEventListener('resize', resizeCharts)
    }

    // 调整图表大小
    const resizeCharts = () => {
      if (timeChartInstance) {
        timeChartInstance.resize()
      }
      if (scoreChartInstance) {
        scoreChartInstance.resize()
      }
    }

    // 获取第一个图表数据
    const fetchTimeData = async () => {
      try {
        timeLoading.value = true
        const response = await axios.get('/api/statistics/exam', {
          params: {
            timeDimension: timeDimension.value
          }
        })
        timeStatisticsData.value = response.data
        renderTimeChart()
      } catch (error) {
        console.error('获取时间维度数据失败:', error)
        ElMessage.error('获取时间维度数据失败: ' + error.message)
      } finally {
        timeLoading.value = false
      }
    }

    // 渲染第一个图表
    const renderTimeChart = () => {
      if (!timeChartInstance || timeStatisticsData.value.length === 0) return

      const timePeriods = timeStatisticsData.value.map(item => item.timePeriod)
      const examCounts = timeStatisticsData.value.map(item => item.examCount)
      const correctRates = timeStatisticsData.value.map(item => item.avgCorrectRate)

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          },
          formatter: function (params) {
            let result = `${params[0].axisValue}<br/>`
            params.forEach(param => {
              result += `${param.seriesName}: ${param.value}${param.seriesName.includes('正确率') ? '%' : ''}<br/>`
            })
            return result
          }
        },
        legend: {
          data: ['考试次数', '平均正确率(%)'],
          top: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: timePeriods,
          axisLabel: {
            rotate: 30,
            interval: Math.ceil(timePeriods.length / 10)
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '考试次数',
            min: 0,
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '正确率(%)',
            min: 0,
            max: 100,
            axisLabel: {
              formatter: '{value}%'
            }
          }
        ],
        series: [
          {
            name: '考试次数',
            type: 'line',
            data: examCounts,
            itemStyle: {
              color: '#5470C6'
            },
            smooth: true
          },
          {
            name: '平均正确率(%)',
            type: 'line',
            yAxisIndex: 1,
            data: correctRates,
            itemStyle: {
              color: '#91CC75'
            },
            smooth: true
          }
        ]
      }

      timeChartInstance.setOption(option)
    }

    // 获取第二个图表数据
    const fetchScoreData = async () => {
      try {
        scoreLoading.value = true
        const response = await axios.get('/score-distribution', {
          params: {
            examType: examType.value
          }
        });
         console.log('分数分布数据:', response.data.data); // 添加这行
        scoreStatisticsData.value = response.data.data
        renderScoreChart()
      } catch (error) {
        console.error('获取分数分布数据失败:', error)
        ElMessage.error('获取分数分布数据失败: ' + error.message)
      } finally {
        scoreLoading.value = false
      }
    }

    // 渲染第二个图表
    const renderScoreChart = () => {
      if (!scoreChartInstance || scoreStatisticsData.value.length === 0) return

      const examTypes = scoreStatisticsData.value.map(item => item.examType)
      const range0_20 = scoreStatisticsData.value.map(item => item.range0_20Percent)
      const range21_40 = scoreStatisticsData.value.map(item => item.range21_40Percent)
      const range41_60 = scoreStatisticsData.value.map(item => item.range41_60Percent)
      const range61_70 = scoreStatisticsData.value.map(item => item.range61_70Percent)
      const range71_80 = scoreStatisticsData.value.map(item => item.range71_80Percent)

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (params) {
            let result = `${params[0].axisValue}<br/>`
            params.forEach(param => {
              const dataIndex = param.dataIndex
              const count = scoreStatisticsData.value[dataIndex][
                param.seriesName.replace('占比', 'Count')
              ]
              result += `${param.seriesName}: ${param.value}% (${count}人)<br/>`
            })
            return result
          }
        },
        legend: {
          data: ['0-20分占比', '21-40分占比', '41-60分占比', '61-70分占比', '71-80分占比'],
          top: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: examTypes
        },
        yAxis: {
          type: 'value',
          name: '百分比(%)',
          min: 0,
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [
          {
            name: '0-20分占比',
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: range0_20,
            itemStyle: {
              color: '#F56C6C'
            }
          },
          {
            name: '21-40分占比',
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: range21_40,
            itemStyle: {
              color: '#E6A23C'
            }
          },
          {
            name: '41-60分占比',
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: range41_60,
            itemStyle: {
              color: '#67C23A'
            }
          },
          {
            name: '61-70分占比',
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: range61_70,
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '71-80分占比',
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: range71_80,
            itemStyle: {
              color: '#909399'
            }
          }
        ]
      }

      scoreChartInstance.setOption(option)
    }

    // 根据正确率获取进度条颜色
    const getProgressColor = (percentage) => {
      const percent = Math.min(100, Math.max(0, percentage)); // 确保在0-100之间
      if (percent >= 80) return '#67C23A';
      if (percent >= 60) return '#E6A23C';
      return '#F56C6C';
    }

    // 生命周期钩子
    onMounted(() => {
      initCharts()
      fetchTimeData()
      fetchScoreData()
    })

    onBeforeUnmount(() => {
      if (timeChartInstance) {
        timeChartInstance.dispose()
      }
      if (scoreChartInstance) {
        scoreChartInstance.dispose()
      }
      window.removeEventListener('resize', resizeCharts)
    })

    return {
      timeChart,
      scoreChart,
      timeDimension,
      examType,
      timeStatisticsData,
      scoreStatisticsData,
      timeLoading,
      scoreLoading,
      fetchTimeData,
      fetchScoreData,
      getProgressColor
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.exam-statistics-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-container {
  margin-bottom: 30px;
}

.data-table {
  margin-top: 30px;
}

.time-dimension-selector,
.exam-type-selector {
  margin-left: 20px;
}

.el-table .cell {
  white-space: nowrap;
}

.el-progress {
  display: inline-block;
  width: 100px;
  margin-right: 10px;
  vertical-align: middle;
}
</style>